from flask import request
from funcy import project
import json
from sqlalchemy.exc import IntegrityError
from flask_restful import abort

from redash import models
from redash.permissions import require_admin
from redash.handlers.base import BaseResource, require_fields, get_object_or_404


class EnumResource(BaseResource):
    def get(self, code):
        enum = models.Enums.get_by_code(code,self.current_org)
        return enum.to_dict()

    def post(self, code):
        req = request.get_json(force=True)
        sql = "update public.enums set items = ARRAY["

        is_array = False
        for item in req:
            if is_array: sql = sql + ","            
            sql = sql+ "\'" + json.dumps(item) + "\'::json"
            is_array = True

        sql =sql + "] where code=\'" + str(code) + "\'"
        sql =sql + " and org_id=" + str(self.current_org.id)
        try:
            models.db.session.execute(sql)
            models.db.session.commit()
        except IntegrityError as e:
            if "value" in str(e):
                abort(400, message="编码已存在：")
            abort(500)

class EnumdeleteResource(BaseResource):
    @require_admin
    def post(self, code):
        enum = models.Enums.get_by_code(code,self.current_org)
        models.db.session.delete(enum)
        models.db.session.commit()
        
class EnumItemsResource(BaseResource):
    def get(self, code):
        enum = models.Enums.get_by_code(code,self.current_org)
        return enum.items


class EnumAllResource(BaseResource):
    def get(self):
        enums = models.Enums.all(self.current_org)
        return [e.to_dict() for e in enums]

    @require_admin
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code", "name"))

        enums = models.Enums(
            code=req["code"],
            name=req["name"],
            org=self.current_org,
        )

        try:
            models.db.session.add(enums)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编码已存在.")
            abort(500)

class EnumcodeResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        tblname = req["tblname"]
        tblfield = req["tblfield"]
        bill_date = req["bill_date"]
        type = req["type"]

        org_id =self.current_org.id
        result = models.Enums.get_code(tblname,tblfield,bill_date,org_id,type)
        return result[0]